class GiteeBlog {
  constructor(owner, repo) {
    this.owner = owner;
    this.file = [];
    this.Text = ""; //正在观看的文章
    this.repo = repo;
    this.begin();
    window.onhashchange = function () {
      this.hashchange();
    }.bind(this);
  }
  async hashchange() {
    let url = location.hash.replace("#", "");
    let hash = url.match(
      /(?<=[https|http]:\/\/gitee.com\/)([\s\S]*?)\/([\s\S]*?)\/blob\/([\s\S]*?)\/([\s\S]*)/
    );
    if (hash) {
      url = `https://gitee.com/api/v5/repos/${hash[1]}/${
        hash[2]
      }/contents/${decodeURI(hash[4])}`;
    } else if (url) {
      //不用管 下面会处理
    } else {
      url = localStorage.getItem("lastPage") || "undifine";
    }
    console.log(url);
    try {
      let lastName = url.match(/\.([a-z]+)$/i)[1];
      console.log(lastName);
      if (url && lastName.toLowerCase() == "md") {
        this.openFile(url);
      } else {
        try {
          let txt = Base64.decode((await this.getInfo(url)).content);
          this.watchText = `<pre><code>${txt}<code></pre>`;
        } catch (err) {
          this.pageError = true;
        }
      }
    } catch (err) {
      this.pageError = true;
    }

    // else{
    // 	this.watchText = localStorage.getItem('lastText') || '空'
    // }
    console.log("载入上次文件");
  }
  async begin() {
    this.hashchange();

    //筛选仓库中的文件
    //必须包裹在一个数组中
    let first = await this.getInfo(
      `https://gitee.com/api/v5/repos/${this.owner}/${this.repo}/contents/`
    );
    this.file = await this.filter(first, "BOOK");
    console.log(this.file);
    console.log("载入仓库中");
    this.tree();
  }
  tree() {
    var setting = {
      view: {
        dblClickExpand: false, //屏蔽掉双击事件
      },
      callback: {
        onClick: function (e, treeId, treeNode) {
          var zTree = $.fn.zTree.getZTreeObj("TREE");
          zTree.expandNode(treeNode);
        },
      },
    };

    var zNodes = this.file;
    $.fn.zTree.init($("#TREE"), setting, zNodes);
  }
  //处理文件夹和文件 只收集md文件  文件夹继续
  // 注意一定是arr 在初次访问时是使用
  async filter(arr, foldName) {
    let section = [];
    let dir = arr.reduce((a, b) => {
      if (b.type == "dir") {
        a.push(b);
      } else if (/\.md$/.test(b.name)) {
        section.push({
          name: b.name,
          target: "_self",
          url: "#" + b.url,
        });
      }
      return a;
    }, []);

    // 开始递归
    let folds = [];
    if (dir.length) {
      let pro = [];
      for (let i = dir.length; i--; ) {
        let res = await this.getInfo(dir[i].url);
        let res2 = await this.filter(res, dir[i].name);
        pro.push(res2);
      }

      folds = await Promise.all(pro);
      folds = folds.filter((i) => i);
    }
    console.log(folds);
    //整层整层放入好处理
    if (section.length || folds.length) {
      return {
        name: foldName,
        isParent: true,
        children: [...section, ...folds],
      };
    }
  }
  //用于向网络请求文件
  async openFile(url) {
    try {
      let txt = Base64.decode((await this.getInfo(url)).content);

      this.watchText = marked.makeHtml(txt);
      this.metadata = marked.getMetadata();
      ScrollToControl();
    } catch (err) {
      this.pageError = true;
    }
  }

  // Gitee 的接口
  async getInfo(url) {
    return await fetch(url).then((res) => res.json());
  }
  async getRepos() {
    return await fetch(
      `https://gitee.com/api/v5/users/${this.owner}/repos`
    ).then((res) => res.json());
  }
  set watchText(txt) {
    this.Text = txt;
    let doc = document.getElementById("md");
    doc.innerHTML = this.Text;
    doc.querySelectorAll("pre>code").forEach((i) => hljs.highlightBlock(i));
    localStorage.setItem("lastText", txt);
    console.log("文件已经打开");
    imgZoom("#md img");
    console.log("放大镜打开");
    this.toclist = [
      ...document.getElementById("md").querySelectorAll("h1,h2,h3,h4,h5,h6"),
    ].map((i, index) => {
      i.id = parseInt(Math.random() * 1000) + "=" + i.tagName;
      return { id: i.id, content: i.innerText };
    });
  }
  set pageError(value) {
    if (value) {
      this.openFile(
        `https://gitee.com/api/v5/repos/${this.owner}/${this.repo}/contents/404.md`
      );
    }
  }
  set toclist(value) {
    console.log("TOC大纲");
    document.getElementById("toc-in").innerHTML = value
      .map(
        (i) =>
          `<li><a data-id='${i.id}' target='_self' onclick='toTitle(event)'>${i.content}</a></li>`
      )
      .join("");
  }
}
